import numpy as np 
import torch 
from torch import nn
from torch.utils import data
from d2l import torch as d2l

# 1. 生成数据集=======
true_w = torch.tensor([2,-3.4])
true_b = 4.2
features,labels = d2l.synthetic_data(true_w,true_b,1000)


# 定义数据集和数据集迭代器
dataset = data.TensorDataset(features,labels)
train_dataloader = data.DataLoader(dataset,batch_size=10,shuffle=True)
# print(next(iter(data_iter)))

# 2. 定义模型==========
net = nn.Sequential(nn.Linear(2,1))

# 3.定义损失函数========
loss = nn.MSELoss()

# 4. 定义优化算法=======
optimizer = torch.optim.SGD(net.parameters(),lr=0.03)

# 5. 训练==============
# 初始化模型参数
net[0].weight.data.normal_(0,0.01)
net[0].bias.data.fill_(0)

# 初始化超参数
num_epochs = 3

for epoch in range(num_epochs):
    for X,y in train_dataloader:
        l = loss(net(X),y)
        optimizer.zero_grad()
        l.backward()
        optimizer.step()
    l = loss(net(features),labels)
    print(f'epoch {epoch + 1}, loss {l:f}')